package com.soc.erp.index;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import org.nature.framework.annotation.Ask;
import org.nature.framework.annotation.Ctrl;
import org.nature.framework.annotation.Inject;
import org.nature.framework.annotation.Redirect;
import org.nature.framework.bean.JsonData;
import org.nature.framework.core.NatureCtrl;
import org.nature.framework.core.NatureMap;
import com.soc.erp.employee.Employee;
import com.soc.erp.operRecord.OperRecordService;
import com.soc.utils.Convert;
 

@Ctrl(namespace = "/index")
public class IndexCtrl extends NatureCtrl {
	
	/**
	 *2018/10/22 by xl 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	IService iService;
	
	@Inject
	OperRecordService operRecordService;
	
	public String login_name;
	public String login_password;
	public String password;
	public String id;
	//public Member member = new Member();
	
	public Employee employee= new Employee(); //创建系统用户
	
	//public Company company = new Company();
	public File license_pic,company_picture;
	public File company_logo;
	
	public String dynamic_password;
	
	public String code;

	@Ask 
	public Object login(){
		return "login.ftl";
		//return "company-login.ftl";//企业登录
	}
	
	@Ask
	public Object welcome() {

		/*int role_type = (int) getSession().getAttribute("role_type");

		if (role_type == 2) { // 
			String dealer_id = (String) getSession().getAttribute(Dealer.dealer_id);
			if (StringUtil.isNotBank(dealer_id)) {
				page.put("statistics", iService.list(String.format("select * from vw_project_statistics where dealer_id='%s'", dealer_id)));
			}
		}*/

		//return "/WEB-INF/view/_frag/welcome.ftl";
		//return "/WEB-INF/view/_frag/welcome.ftl";
		return "/asset/hui/welcome.html";
	}
	
	@Ask
	public Object welcome1() {

		 
		return "/WEB-INF/view/index/welcome1.ftl";
	}
	
	
	@Ask
	public Object company_welcome() {
		return "/WEB-INF/view/index/welcome2.ftl";
	}
	/*
	 * 登录验证
	 * */
	@Ask
	@Redirect
	public Object checkout(){	
			//验证码
			/*String valiCode = (String)getSession().getAttribute("valiCode");
			if(!valiCode.toLowerCase().equals(code.toLowerCase())){
					return new JsonData(-1);
			}*/
			
			//两种账号不能同时登陆 2017.09.23
			/*if (null != getSession().getAttribute("login_name")) {
				return new JsonData(-2);
			}*/
			
		 
			int result = 0; 
			String sql="select * from HR_Employee where cEMName = '"+login_name+"'";
			NatureMap loginmap = iService.unique(sql);
			
			//System.out.println(sql);
			//String sha1_login_password = iService.sha1(password);//m5d加密
			
			if (!loginmap.getString("cEMPassword").equals(password)) {
				result = 0;				 
			} else {
				result = 1;
				getSession().setAttribute("login_name", loginmap.getString(Employee.cEMName));
				 
				getSession().setAttribute("employee_id", loginmap.getString(Employee.cEMNo));
				//getSession().setAttribute("dealer_id", null);
				getSession().setAttribute("permit", loginmap.getString(Employee.nEMPermit));
				
				/*增加权限*/
				List<String> opeList = new ArrayList<String>();
				sql = String.format("SELECT perm_id FROM tb_role_perm WHERE role_id='%s'", loginmap.getString(Employee.nEMPermit));
				List<NatureMap> ops = iService.list(sql);
				for (NatureMap op : ops) {
					opeList.add(op.getString("perm_id"));
				}
				getSession().setAttribute("opeList", opeList);
				getSession().setAttribute("perms", Convert.getPERMs());//所有权限
				System.out.println(opeList);
				//getSession().setAttribute("role_type", 0); //0代表管理员
				/*operRecordService.insertOper("管理员登录系统！");*/
			}
			
			return new JsonData(result);
	}
	
	/**
	 * 首页
	 */
	@Ask
	public Object index(){
		 
		return "index.ftl";
	}

	@Ask
	//@Redirect
	public Object logout() {
		
		//operRecordService.insertOper("退出系统！");
		/*
		getSession().setAttribute("real_name", null);
		getSession().setAttribute("member_id", null);*/
		getSession().setAttribute("login_name", null);
		return "login.ftl";
		//return "admin";
	}
	


	 
	
	//登录
	@Ask
	public Object admin(){
		getSession().setAttribute("login_name", null);
		getSession().setAttribute("real_name", null);
		//getSession().setAttribute("member_id", null);
		return "login.ftl";
		//return "/WEB-INF/view/index/login.ftl";
	}
		
	 
	
	
	//企业 账号密码登录 给该企业号设置权限
	@Ask
	@Redirect
	public Object verify_password() {
		//验证码
		String valiCode = (String)getSession().getAttribute("valiCode");
		if(!valiCode.toLowerCase().equals(code.toLowerCase())){
			return new JsonData(-1);
		}
		
		//两种账号不能同时登陆 2017.09.23
		/*if (null != getSession().getAttribute("login_name")) {
			return new JsonData(-2);
		}*/
		
		int res = 0;
		//String sql = "select * from tb_company_info where login_name='" + login_name + "'";
		//System.out.println(sql);
		//NatureMap loginmap = iService.unique(sql);
		//String sha1_login_password = iService.sha1(login_password);
		/*if ((StringUtil.isNotBank(loginmap.getString(Company.login_password))) && (loginmap.getString(Company.login_password).equals(login_password))) {
			
			if("0".equals(loginmap.getString(Company.audit_state))){
				res=2;//2表示正在审核中,请耐心等待
			}else if("1".equals(loginmap.getString(Company.deleted))){
				res=3;//3标示该账号已被注销，请重新注册
			}else if("2".equals(loginmap.getString(Company.audit_state))){
				res=4;//4表示审核不通过
			}
			else{
				res = 0;//成功登录
				getSession().setAttribute("login_name", loginmap.getString(Company.login_name));
				getSession().setAttribute("company_name", loginmap.getString(Company.contact_name));
				getSession().setAttribute("company_id", loginmap.getString(Company.company_id));
				//getSession().setAttribute("member_id", null);
				增加权限
				List<String> opeList = new ArrayList<String>();
				sql = String.format("SELECT permit_id FROM tb_role_permit WHERE role_id='%s'", loginmap.getString(Company.role_id));
				List<NatureMap> ops = iService.list(sql);
				for (NatureMap op : ops) {
					opeList.add(op.getString("permit_id"));
				}
				getSession().setAttribute("opeList", opeList);
				getSession().setAttribute("perms", Convert.getPERMs());//所有权限
				System.out.println("该公司所有权限有："+opeList);
				getSession().setAttribute("role_type", 2); //企业
				operRecordService.insertOper("企业登录系统！");
				
				//return "company_index";
				
			}
			
			
		} 
		else
		{
			res = 1;
		}
		*/
		return new JsonData(res);
	}
	
	 
	
	//
	@Ask
	public Object company_index(){
		return "company-index.ftl";
	}
	
	//跳转公司注册页面
	@Ask
	public Object register() {
		
		List<NatureMap> company_nature = iService.list("SELECT c_key,c_value FROM tb_system_config where  item = 'company_nature' order by c_key");
		page.put("company_nature", company_nature);
		
		List<NatureMap> company_scale = iService.list("SELECT c_key,c_value FROM tb_system_config where  item = 'company_scale' order by c_key");
		page.put("company_scale", company_scale);
		
		List<NatureMap> company_industry = iService.list("SELECT c_key,c_value FROM tb_system_config where  item = 'company_industry' order by c_key");
		page.put("company_industry", company_industry);
		
		return "register.ftl";
	}
	
	//公司注册
	@Ask
	public Object company_register(){
		/*if (SmsCtrl.validateCode(company.getString(Company.contact_mobile), dynamic_password) == 0) {
			return new JsonData(2);
		}
		
		if ((StringUtil.isBank(company.getString(Company.company_province))) || (StringUtil.isBank(company.getString(Company.company_city)))) {
			return new JsonData(4);
		}*/
		
		//if (StringUtil.isNotBank(company.getString(Company.login_name))) {
		//	String sql = String.format("select count(*) from tb_company_info where login_name='%s' and (audit_state=0 or audit_state=1) and disabled_state=0", company.getString(Company.login_name));
		//2018-9-24 营业执照如果有重复 不操作数据
		/*if (StringUtil.isNotBank(company.getString(Company.licence_number))) {
			String sql = String.format("select count(*) from tb_company_info where licence_number='%s' and (audit_state=0 or audit_state=1) and disabled_state=0", company.getString(Company.licence_number));
			
			Object cnt = iService.uniqueValue(sql);
			if (CastUtil.castInt(cnt) == 0) {
				if (license_pic!=null) {
					String path = getRealPath()+File.separatorChar+"LicensePics"+File.separatorChar+license_pic.getName();
					File file = new File(path);
					file.getParentFile().mkdirs();
					company.put(Company.company_licence, "LicensePics"+File.separatorChar+license_pic.getName());
					FileUtil.move(license_pic, file);
				}
				
				//20180820新增
				if (company_logo!=null) {
					String path = getRealPath()+File.separatorChar+"LogoPics"+File.separatorChar+company_logo.getName();
					File file = new File(path);
					file.getParentFile().mkdirs();
					company.put(Company.company_logo, "LogoPics"+File.separatorChar+company_logo.getName());
					FileUtil.move(company_logo, file);
				}
				//company.put(Company.login_password, iService.sha1(company.getString(Company.login_password)));
				
				//20180825新增
				if (company_picture!=null) {
					String path = getRealPath()+File.separatorChar+"CompanyPics"+File.separatorChar+company_picture.getName();
					File file = new File(path);
					file.getParentFile().mkdirs();
					company.put(Company.company_picture, "CompanyPics"+File.separatorChar+company_picture.getName());
					FileUtil.move(company_picture, file);
				}
				
				company.put(Company.login_password, company.getString(Company.login_password));
				
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				company.put(Company.register_time, df.format(new Date()));
				
				company.put(Company.audit_state, 0);
				company.put(Company.disabled_state, 0);
				company.put(Company.deleted, 0);
				company.put(Company.role_id, 3);//默认角色
				
				iService.insert(company);
				
				return new JsonData(0);
			} else {
				return new JsonData(1);
			}
		}
		*/
		return new JsonData(3);
	}
	
	
	 // 设置字母的大小,大小
    private Font mFont = new Font("宋体", Font.BOLD, 28);
    public String valiCode;//验证码
    public String a;
	@Ask
	public void writeImgae() throws IOException{
        // 创建画板缓冲区
        int width = 100;
        int height = 45;
        BufferedImage img = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 获取画板
        Graphics g = img.getGraphics();
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, width, height);//填充颜色
        g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);// 画出边框
        // 画随机线
        Random random = new Random();
        for (int i = 0; i < 15; i++) {
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height - 1);
            int xl = random.nextInt(12) + 1;
            int yl = random.nextInt(48) + 1;
            g.setColor(new Color(random.nextInt(255), random.nextInt(5), random
                    .nextInt(10)));
            g.drawLine(x, y, x + xl, y + yl);
        }
        // 画上字符串
        g.setColor(new Color(25, 11, 222));
        g.setFont(mFont);
        String[] chars = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "s",
                "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "S", "Y", "Z" };
        //System.out.println(chars.length);
        valiCode = "";
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(62);
            int rc = random.nextInt(256);
            int gc = random.nextInt(256);
            int bc = random.nextInt(25);
            g.setColor(new Color(rc, gc, bc));
            g.drawString(chars[index], 20 * i + 5, 30);
            valiCode += chars[index];
        }
        g.dispose();
        g.dispose();
        HttpSession session = getSession();
        //System.out.println(valiCode);
        session.setAttribute("valiCode", valiCode);
        ImageIO.write(img, "JPEG", getResponse().getOutputStream());
	}
}
